﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Text;

namespace Anno
{
    public static class JsonHelper
    {
        static Newtonsoft.Json.Converters.IsoDateTimeConverter timeFormat = new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
        public static byte[] SerializeObject(this object value)
        {
            if (value.IsNullOrDBNull_()) return null;
            return UTF8Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value, timeFormat));
        }

        public static object DeserializeObject(this byte[] value, Type type)
        {
            if (value.Length == 0)
            {
                return null;
            }
            return JsonConvert.DeserializeObject(UTF8Encoding.UTF8.GetString(value), type, timeFormat);
        }
        public static object DeserializeObjectByJson(this string value)
        {
            if (value.IsNullOrDBNull_()) return null;
            return JsonConvert.DeserializeObject(value, null, timeFormat);
        }
        public static object DeserializeObjectByJson(this string value, Type type)
        {
            if (value.IsNullOrDBNull_()) return null;
            return JsonConvert.DeserializeObject(value, type, timeFormat);
        }
        public static T DeserializeObjectByJson<T>(this string value)
        {
            return (T)DeserializeObjectByJson(value, typeof(T));
        }

        public static string SerializeObjectToJson(this object value)
        {
            if (value.IsNullOrDBNull_()) return "";
            return JsonConvert.SerializeObject(value, timeFormat);
        }

        public static T DeserializeObject<T>(this byte[] value)
        {
            if (value.Length == 0)
            {
                return default(T);
            }
            return (T)DeserializeObject(value, typeof(T));
        }

        /// <summary>
        /// string字典
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
        {
            if (string.IsNullOrEmpty(jsonStr))
                return new Dictionary<TKey, TValue>();

            Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);

            return jsonDict;
        }

    }
}
